package com.sen.design.pattern.creational.prototype.clone;

import com.sen.design.pattern.creational.singleton.HungrySingleton;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 原型模式：浅克隆，深克隆
 */
public class Test {
    public static void main(String[] args) throws CloneNotSupportedException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Date birthday = new Date(0L);
        Pig pig1 = new Pig("佩奇", birthday);
        Pig pig2 = (Pig) pig1.clone();
        System.out.println("pig1 = " + pig1);
        System.out.println("pig2 = " + pig2);
        System.out.println("=======================");
        pig1.getBirthday().setTime(666666666666L);
        System.out.println("pig1 = " + pig1);
        System.out.println("pig2 = " + pig2);

        // 原型模式重写clone方法破坏单例；应返回getInstance方法
//        HungrySingleton hungrySingleton = HungrySingleton.getInstance();
//        Method clone = hungrySingleton.getClass().getDeclaredMethod("clone");
//        clone.setAccessible(true);
//        HungrySingleton invoke = (HungrySingleton) clone.invoke(hungrySingleton);
//        System.out.println("hungrySingleton = " + hungrySingleton);
//        System.out.println("invoke = " + invoke);
    }
}
